package com.fcbox.conf;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.lang.invoke.MethodHandles;

/**
 * edms
 * Created by 000498 on 2016/11/30.
 */
@Configuration
@MapperScan(basePackages = "com.fcbox.mapper.edms", sqlSessionFactoryRef = EdmsDataSourceConfig.SQL_SESSION_FACTORY_NAME)
public class EdmsDataSourceConfig {
	public static final String SQL_SESSION_FACTORY_NAME = "sessionFactoryEdms";
	public static final String TX_MANAGER = "txManagerEdms";
	private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

	@Bean(name = "datasourceEdms")
	@Primary
	@ConfigurationProperties(prefix = "datasource.edms")
	public DataSource dataSourceEdms() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = TX_MANAGER)
	@Primary
	public PlatformTransactionManager txManagerKm() {
		return new DataSourceTransactionManager(dataSourceEdms());
	}

	@Bean(name = EdmsDataSourceConfig.SQL_SESSION_FACTORY_NAME)
	@Primary
	public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSourceEdms());
		//扫描classpath:/mapper/*Mapper.xml下的xml
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*Mapper.xml"));
		return sqlSessionFactoryBean.getObject();
	}
}
